package ua.edu.nuos.jeetraining2012.automator.services.bl.services.ru;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.simple.JSONObject;
import org.json.simple.parser.ParseException;
import ua.edu.nuos.jeetraining2012.automator.services.bl.common.services.translate.ITranslateService;
import ua.edu.nuos.jeetraining2012.automator.services.common.api.dao.http.JsonHttpClient;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Timur Yarosh
 *         Date: 08.06.13
 *         Time: 18:59
 */
public class YandexTranslateService implements ITranslateService {
    private final String DEVELOPER_KEY = "trnsl.1.1.20130608T175449Z.65883b07c3ac918e.8c47a5492e61d1b85b734ecbd275a86651eb54f7";
    private final String API_TRANSLATE_URL = "https://translate.yandex.net/api/v1.5/tr.json/translate";
    private final String API_DEVELOPER_KEY_PARAMETER = "key";
    private final String API_DIRECTION_PARAMETER = "lang";
    private final String API_TEXT_PARAMETER = "text";
    @Override
    public String translate(String direction, String... text) throws IOException, ParseException {
        StringBuilder reponse = new StringBuilder();
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair(API_DEVELOPER_KEY_PARAMETER, DEVELOPER_KEY));
        params.add(new BasicNameValuePair(API_DIRECTION_PARAMETER, direction));
        for (String s : text) {
            params.add(new BasicNameValuePair(API_TEXT_PARAMETER, s));
        }
        JSONObject response = JsonHttpClient.post(API_TRANSLATE_URL, params);
        List<String> responseList = (List<String>) response.get("text");
        for (String reponseText : responseList) {
            reponse.append(reponseText);
        }
        return reponse.toString();
    }
}
